// pages/patient-select/patient-select.js
Page({
	data: {
		selectedPatient: null,
		patientList: []
	},

	onLoad() {
		this.fetchPatients()
	},

	fetchPatients() {
		wx.showLoading({ title: '加载中...' })
		wx.request({
			url: 'http://localhost:8005/patient/list',
			method: 'GET',
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				wx.hideLoading()
				if (res.statusCode === 200 && res.data) {
					let list = res.data
					if (typeof list === 'string') {
						try { list = JSON.parse(list) } catch (e) { return }
					}
					if (list.code !== undefined) list = list.data
					if (!Array.isArray(list)) return
					const mapped = list.map(p => ({
						id: p.id,
						name: p.name,
						relation: p.relationTypeName || '本人',
						idNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
						isDefault: p.isDefault === 1
					}))
					this.setData({ patientList: mapped })
				}
			},
			fail: () => { wx.hideLoading() }
		})
	},

	selectPatient(e) {
		const patient = e.currentTarget.dataset.patient
		this.setData({ selectedPatient: patient })
		const cacheUser = wx.getStorageSync('userInfo') || {}
		wx.setStorageSync('userInfo', { ...cacheUser, patientId: patient.id })
		wx.navigateTo({
			url: `/pages/department-select/department-select?patientId=${patient.id}`
		})
	},

	addPatient() {
		wx.showToast({ title: '添加就诊人功能', icon: 'none', duration: 2000 })
	}
})